﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PlasmaMes.A_Models;
using PlasmaMes.A_Models.ResponseClass;
using PlasmaMes.Services;
using static System.Net.WebRequestMethods;

namespace PlasmaMes
{
    public partial class Form_Mes: Form
    {
        public BindingList<BingSnList> bingSnList = new BindingList<BingSnList>();

        public Form_Mes()
        {
            InitializeComponent();
        }

        private void Form_Mes_Load(object sender, EventArgs e)
        {
           
            DataGridViewInit();

            uiDataGridView_绑定_条码列表.RowCount = 1;
            uiDataGridView_解绑_条码集合.RowCount = 1;


            this.uiDataGridView_绑定_条码列表.RowPostPaint += new DataGridViewRowPostPaintEventHandler(this.dgv_RowPostPaint);
            this.uiDataGridView_解绑_条码集合.RowPostPaint += new DataGridViewRowPostPaintEventHandler(this.dgv_RowPostPaint);

            uiDataGridView_绑定_条码列表.DataSource = bingSnList;
        }

        private void dgv_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                e.RowBounds.Location.Y,
                uiDataGridView_绑定_条码列表.RowHeadersWidth - 4,
                e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                uiDataGridView_绑定_条码列表.RowHeadersDefaultCellStyle.Font,
                rectangle,
                uiDataGridView_绑定_条码列表.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void DataGridViewInit()
        {
          
            DataGridViewColumn column = new DataGridViewTextBoxColumn();
            column.Width = 250;
            column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            column.DataPropertyName = "Sn";
            column.HeaderText = "条码";
            uiDataGridView_绑定_条码列表.Columns.Add(column);

            DataGridViewColumn column1 = new DataGridViewTextBoxColumn();
            column1.Width = 250;
            column1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            column1.DataPropertyName = "CavityNumber";
            column1.HeaderText = "穴位";
            uiDataGridView_绑定_条码列表.Columns.Add(column1);


            DataGridViewColumn column2 = new DataGridViewTextBoxColumn();
            column2.Width = 340;
            column2.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            column2.DataPropertyName = "Sn";
            column2.HeaderText = "条码";
            uiDataGridView_解绑_条码集合.Columns.Add(column2);

        }

        private async void bt_Token获取请求_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(tb_网站前缀.Text))
            {
                MessageBox.Show("网站前缀不能为空");
                return;
            }


            if(string.IsNullOrEmpty(tb_Token_设备资产编码.Text))
            {
                MessageBox.Show("设备资产编码不能为空");
                return;
            }

            if (string.IsNullOrEmpty(tb_Token_工厂编码.Text))
            {
                MessageBox.Show("工厂编码不能为空");
                return;
            }

            string url = tb_网站前缀.Text + "/GtkPMF.MetalMes.AutoLineInterface/api/token/GetToken";

            TokenGet tokenGet = new TokenGet();

            tokenGet.userCode = tb_Token_设备资产编码.Text;   
            tokenGet.factoryCode = tb_Token_工厂编码.Text;
            tokenGet.timeStamp = DateTime.Now.ToString();

            await PostRequest(url, tokenGet);

            var tokenResponse = JsonHelper.JsonStringToObj<TokenResponse>(MesService.Instance.responseBody);

            this.BeginInvoke((MethodInvoker)delegate { tb_token.Text = tokenResponse.Data.Token; });
          

            UpdateRichTextBox(MesService.Instance.responseBody);
        }

        private async void bt_产品sn获取请求_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tb_sn_工序代码.Text))
            {
                MessageBox.Show("工序代码不能为空");
                return;
            }


            if (string.IsNullOrEmpty(tb_sn_工站代码.Text))
            {
                MessageBox.Show("工站代码不能为空");
                return;
            }

            if (string.IsNullOrEmpty(tb_sn_工装编码.Text))
            {
                MessageBox.Show("工装编码不能为空");
                return;
            }

            if(string.IsNullOrEmpty(tb_token.Text))
            {
                MessageBox.Show("Token不能为空, 请先获取Token");
                return;
            }


            string url = tb_网站前缀.Text + "/GtkPMF.MetalMes.AutoLineInterface/api/moldingline/getsnbytool";

            ProductSnGet productSnGet = new ProductSnGet(); 

            productSnGet.token = tb_token.Text;
            productSnGet.StageCode = tb_sn_工序代码.Text;
            productSnGet.StationCode = tb_sn_工站代码.Text;
            productSnGet.ToolCode = tb_sn_工装编码.Text;

            await PostRequest(url, productSnGet);

            UpdateRichTextBox(MesService.Instance.responseBody);


        }

        private async void bt_工装解绑请求_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tb_token.Text))
            {
                MessageBox.Show("Token不能为空, 请先获取Token");
                return;
            }
            if (string.IsNullOrEmpty(tb_解绑工序.Text))
            {
                MessageBox.Show("解绑工序不能为空");
                return;
            }
            if (string.IsNullOrEmpty(tb_解绑工站.Text))
            {
                MessageBox.Show("解绑工站不能为空");
                return;
            }
            if (string.IsNullOrEmpty(tb_解绑设备资产编号.Text))
            {
                MessageBox.Show("解绑设备资产编号不能为空");
                return;
            }
            if (string.IsNullOrEmpty(tb_解绑工装编码.Text))
            {
                MessageBox.Show("解绑工装编码不能为空");
                return;
            }
            if (string.IsNullOrEmpty(tb_解绑类型.Text))
            {
                MessageBox.Show("解绑类型不能为空");
                return;
            }
            //if (string.IsNullOrEmpty(tb_解绑条码集合.Text))
            //{
            //    MessageBox.Show("解绑条码集合不能为空");
            //    return;
            //}
            //if (string.IsNullOrEmpty(tb_解绑条码.Text))
            //{
            //    MessageBox.Show("解绑条码不能为空");
            //    return;
            //}


            string url = tb_网站前缀.Text + "/GtkPMF.MetalMes.AutoLineInterface/api/moldingline/toolunbindsn";

            UnbindInfo unbindInfo = new UnbindInfo();

            unbindInfo.token = tb_token.Text;
            unbindInfo.StageCode = tb_解绑工序.Text;        
            unbindInfo.StationCode = tb_解绑工站.Text;
            unbindInfo.AssetNo = tb_解绑设备资产编号.Text;
            unbindInfo.SnList = new List<string>();
            foreach (DataGridViewRow row in uiDataGridView_解绑_条码集合.Rows)
            {
                // 检查当前行是否不是新行（未提交的空行）
                if (!row.IsNewRow)
                {
                    // 假设你的唯一一列的索引是0，或者使用列名代替
                    string sn = row.Cells[0].Value.ToString();
                    if (!string.IsNullOrEmpty(sn))
                    {
                        unbindInfo.SnList.Add(sn);
                    }
                   
                }
            }

            unbindInfo.ToolCode = tb_解绑工装编码.Text;
            unbindInfo.Type = tb_解绑类型.Text;

            await PostRequest(url, unbindInfo);

            UpdateRichTextBox(MesService.Instance.responseBody);

        }

        private async void bt_工装绑定请求_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tb_token.Text))
            {
                MessageBox.Show("Token不能为空, 请先获取Token");
                return;
            }

            if (string.IsNullOrEmpty(tb_绑定工序.Text))
            {
                MessageBox.Show("绑定工序不能为空");
                return;
            }
            if(string.IsNullOrEmpty(tb_校验_工站.Text))
            {
                MessageBox.Show("绑定工站不能为空");
                return;
            }
            if (string.IsNullOrEmpty(tb_绑定_设备资产编号.Text))
            {
                MessageBox.Show("绑定设备资产不能为空");
                return;
            }
            
            if (string.IsNullOrEmpty(tb_绑定_工装编码.Text))
            {
                MessageBox.Show("绑定工站不能为空");
                return;
            }
            if (string.IsNullOrEmpty(tb_绑定_工装绑定类型.Text))
            {
                MessageBox.Show("绑定工站不能为空");
                return;
            }

            string url = tb_网站前缀.Text + "/GtkPMF.MetalMes.AutoLineInterface/api/moldingline/toolbindsn";

            BingInfo bingInfo = new BingInfo();
            bingInfo.token = tb_token.Text.Trim();
            bingInfo.StageCode = tb_校验_工序.Text.Trim();
            bingInfo.StationCode = tb_校验_工站.Text.Trim();
            bingInfo.AssetNo = tb_绑定_设备资产编号.Text.Trim();
            bingInfo.SnList = new List<BingSnList>();
            
            for (int i = 0;i< bingSnList.Count;i++)
            {
                BingSnList snlist = new BingSnList();
                snlist.Sn = bingSnList[i].Sn;
                snlist.CavityNumber = bingSnList[i].CavityNumber;
                bingInfo.SnList.Add(snlist);
            }

            bingInfo.ToolCode = tb_绑定_工装编码.Text.Trim();
            bingInfo.Type = tb_绑定_工装绑定类型.Text.Trim();

            await PostRequest(url, bingInfo);

            UpdateRichTextBox(MesService.Instance.responseBody);
        }

        private async void bt_条码路由校验请求_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tb_token.Text))
            {
                MessageBox.Show("Token不能为空, 请先获取Token");
                return;
            }
            if (string.IsNullOrEmpty(tb_校验_设备资产编号.Text))
            {
                MessageBox.Show("设备资产编号不能为空");
                return;
            }
            if (string.IsNullOrEmpty(tb_校验_工序.Text))
            {
                MessageBox.Show("工序不能为空");
                return;
            }
            if (string.IsNullOrEmpty(tb_校验_工站.Text))
            {
                MessageBox.Show("工站不能为空");
                return;
            }
            if (string.IsNullOrEmpty(tb_校验_产品SN.Text))
            {
                MessageBox.Show("产品SN不能为空");
                return;
            }

            string url = tb_网站前缀.Text + "/GtkPMF.MetalMes.AutoLineInterface/api/sninfo/SnCheckRoute";

            BarcodeCheck barcodeCheck = new BarcodeCheck();
            barcodeCheck.token = tb_token.Text;
            barcodeCheck.StationCode = tb_校验_工站.Text;
            barcodeCheck.AssetNo = tb_校验_设备资产编号.Text.Trim();
            barcodeCheck.StageCode = tb_校验_工序.Text;
            barcodeCheck.Sn = tb_校验_产品SN.Text;

            await PostRequest(url, barcodeCheck);

            UpdateRichTextBox(MesService.Instance.responseBody);
        }

        private async void bt_过站请求_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tb_token.Text))
            {
                MessageBox.Show("Token不能为空, 请先获取Token");
                return;
            }

            if(string.IsNullOrEmpty(tb_过站_设备资产编号.Text))
            {
                MessageBox.Show("设备资产编号不能为空");
                return; 
            }
            if (string.IsNullOrEmpty(tb_过站_工序.Text))
            {
                MessageBox.Show("工序不能为空");
                return;
            }
            if (string.IsNullOrEmpty(tb_过站_工站.Text))
            {
                MessageBox.Show("工站不能为空");
                return;
            }
            if (string.IsNullOrEmpty(tb_过站_产品sn.Text))
            {
                MessageBox.Show("产品sn不能为空");
                return;
            }
            if (string.IsNullOrEmpty(tb_过站_是否完工节点.Text))
            {
                MessageBox.Show("完工节点不能为空");
                return;
            }
            if (string.IsNullOrEmpty(tb_过站_是否系统扣料.Text))
            {
                MessageBox.Show("系统扣料不能为空");
                return;
            }

            string url = tb_网站前缀.Text + "/GtkPMF.MetalMes.AutoLineInterface/api/sninfo/SnPassStation";

            BarcodePass barcodePass = new BarcodePass();
            barcodePass.token = tb_token.Text;
            barcodePass.AssetNo = tb_过站_设备资产编号.Text;
            barcodePass.StageCode = tb_过站_工序.Text.Trim();
            barcodePass.StationCode = tb_过站_工站.Text;
            barcodePass.Sn = tb_过站_产品sn.Text;
            barcodePass.IsFinished = tb_过站_是否完工节点.Text;
            barcodePass.DeductMaterials = tb_过站_是否系统扣料.Text;
            barcodePass.IsOK = tb_过站_是否良品.Text;

            await PostRequest(url, barcodePass);

            UpdateRichTextBox(MesService.Instance.responseBody);
        }

        

        private static async Task GetRequest(string url, object obj)
        {
            using (HttpClient client = new HttpClient())
            {
                // 替换为你的目标URL
                // string url = "http://example.com/api/resource";

                try
                {
                    HttpResponseMessage response = await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\n异常捕获!");
                    Console.WriteLine(e.Message);
                }
            }
        }


        private static async Task PostRequest(string url, object obj)
        {
            using (HttpClient client = new HttpClient())
            {

                var content = new StringContent(JsonHelper.ObjToJsonString(obj), Encoding.UTF8, "application/json");

                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, content);
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();

                    MesService.Instance.responseBody = responseBody;

                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\n异常捕获!");
                    Console.WriteLine(e.Message);
                }
            }
        }


        private void UpdateRichTextBox(string msg)
        {
            this.BeginInvoke((MethodInvoker)delegate {

                if (uiRichTextBox1.Lines.Length != 0)
                {
                    uiRichTextBox1.AppendText("\n返回的数据：\n " + msg);
                }
                else
                {
                    uiRichTextBox1.AppendText("返回的数据：\n " + msg);
                }

                uiRichTextBox1.ScrollToCaret();

            });
        }

        private void uiSymbolButton_绑定_add_Click(object sender, EventArgs e)
        {
            bingSnList.Add(new BingSnList());
        }

        private void uiSymbolButton_绑定_del_Click(object sender, EventArgs e)
        {
            bingSnList.RemoveAt(bingSnList.Count - 1);
        }

        private void uiSymbolButton_解绑_条码集合_add_Click(object sender, EventArgs e)
        {
            uiDataGridView_解绑_条码集合.RowCount++;
        }

        private void uiSymbolButton_解绑_条码集合_del_Click(object sender, EventArgs e)
        {
            uiDataGridView_解绑_条码集合.Rows.RemoveAt(uiDataGridView_解绑_条码集合.RowCount - 1);
        }
    }
}
